/**
 * Copyright (c) 2021 XuSaisai
 * ArcProgressStackViewJS is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

export class CanvasRotateUtil {
    radius = 0
    startAngled = 0
    startCenterX = 0
    startCenterY = 0
    hasRotate= 0
    hasTranslateX= 0
    hasTranslateY= 0

    constructor(ctxWidth, ctxHeight) {
        this.radius = Math.sqrt(ctxWidth * ctxWidth / 4 + ctxHeight * ctxHeight / 4)
        this.startAngled = Math.atan(ctxHeight / ctxWidth) * 180 / Math.PI
        this.startCenterX = this.getCoordinatesX(-this.startAngled, this.radius) // 初始位置中心点X坐标
        this.startCenterY = this.getCoordinatesY(-this.startAngled, this.radius) // 初始位置中心点Y坐标
    }

    rotate(ctx, rotate) {
        var newX = this.getCoordinatesX(-this.startAngled - rotate, this.radius) // 旋转后位置中心点X坐标
        var newY = this.getCoordinatesY(-this.startAngled - rotate, this.radius) // 旋转后位置中心点Y坐标
        var translateX = this.startCenterX - newX // 需要位移的X距离
        var translateY = newY - this.startCenterY // 需要位移的Y距离
        ctx.rotate((-this.hasRotate) * Math.PI / 180); // 先将画布旋转恢复为原样
        ctx.translate(translateX - this.hasTranslateX, translateY - this.hasTranslateY); // 将画布中心点位移到初始位置的中心点
        ctx.rotate(rotate * Math.PI / 180); // 最后再旋转画布到最新的旋转角度
        // 记录旋转和位移的数值，用于下一次旋转和位移之前恢复
        this.hasTranslateX = translateX
        this.hasTranslateY = translateY
        this.hasRotate = rotate
    }

    getCoordinatesX(angled, radius) {
        return Math.cos(angled * Math.PI / 180) * radius
    }

    getCoordinatesY(angled, radius) {
        return Math.sin(angled * Math.PI / 180) * radius
    }
}